/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistence;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.MaterialConstruccion;
import entities.MedidaMaterial;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import persistence.exceptions.IllegalOrphanException;
import persistence.exceptions.NonexistentEntityException;
import persistence.exceptions.PreexistingEntityException;
import persistence.exceptions.RollbackFailureException;

/**
 *
 * @author Felipe Duarte
 */
@ManagedBean
@RequestScoped
public class MedidaMaterialJpaController implements Serializable {

    public MedidaMaterialJpaController() {
    }

    
    public MedidaMaterialJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(name="TECHO-FFICEPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(MedidaMaterial medidaMaterial) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (medidaMaterial.getMaterialConstruccionList() == null) {
            medidaMaterial.setMaterialConstruccionList(new ArrayList<MaterialConstruccion>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<MaterialConstruccion> attachedMaterialConstruccionList = new ArrayList<MaterialConstruccion>();
            for (MaterialConstruccion materialConstruccionListMaterialConstruccionToAttach : medidaMaterial.getMaterialConstruccionList()) {
                materialConstruccionListMaterialConstruccionToAttach = em.getReference(materialConstruccionListMaterialConstruccionToAttach.getClass(), materialConstruccionListMaterialConstruccionToAttach.getIdMaterialConstruccion());
                attachedMaterialConstruccionList.add(materialConstruccionListMaterialConstruccionToAttach);
            }
            medidaMaterial.setMaterialConstruccionList(attachedMaterialConstruccionList);
            em.persist(medidaMaterial);
            for (MaterialConstruccion materialConstruccionListMaterialConstruccion : medidaMaterial.getMaterialConstruccionList()) {
                MedidaMaterial oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListMaterialConstruccion = materialConstruccionListMaterialConstruccion.getMedidaMaterialIdMedidaMaterial();
                materialConstruccionListMaterialConstruccion.setMedidaMaterialIdMedidaMaterial(medidaMaterial);
                materialConstruccionListMaterialConstruccion = em.merge(materialConstruccionListMaterialConstruccion);
                if (oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListMaterialConstruccion != null) {
                    oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListMaterialConstruccion.getMaterialConstruccionList().remove(materialConstruccionListMaterialConstruccion);
                    oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListMaterialConstruccion = em.merge(oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListMaterialConstruccion);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findMedidaMaterial(medidaMaterial.getIdMedidaMaterial()) != null) {
                throw new PreexistingEntityException("MedidaMaterial " + medidaMaterial + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(MedidaMaterial medidaMaterial) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            MedidaMaterial persistentMedidaMaterial = em.find(MedidaMaterial.class, medidaMaterial.getIdMedidaMaterial());
            List<MaterialConstruccion> materialConstruccionListOld = persistentMedidaMaterial.getMaterialConstruccionList();
            List<MaterialConstruccion> materialConstruccionListNew = medidaMaterial.getMaterialConstruccionList();
            List<String> illegalOrphanMessages = null;
            for (MaterialConstruccion materialConstruccionListOldMaterialConstruccion : materialConstruccionListOld) {
                if (!materialConstruccionListNew.contains(materialConstruccionListOldMaterialConstruccion)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain MaterialConstruccion " + materialConstruccionListOldMaterialConstruccion + " since its medidaMaterialIdMedidaMaterial field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<MaterialConstruccion> attachedMaterialConstruccionListNew = new ArrayList<MaterialConstruccion>();
            for (MaterialConstruccion materialConstruccionListNewMaterialConstruccionToAttach : materialConstruccionListNew) {
                materialConstruccionListNewMaterialConstruccionToAttach = em.getReference(materialConstruccionListNewMaterialConstruccionToAttach.getClass(), materialConstruccionListNewMaterialConstruccionToAttach.getIdMaterialConstruccion());
                attachedMaterialConstruccionListNew.add(materialConstruccionListNewMaterialConstruccionToAttach);
            }
            materialConstruccionListNew = attachedMaterialConstruccionListNew;
            medidaMaterial.setMaterialConstruccionList(materialConstruccionListNew);
            medidaMaterial = em.merge(medidaMaterial);
            for (MaterialConstruccion materialConstruccionListNewMaterialConstruccion : materialConstruccionListNew) {
                if (!materialConstruccionListOld.contains(materialConstruccionListNewMaterialConstruccion)) {
                    MedidaMaterial oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion = materialConstruccionListNewMaterialConstruccion.getMedidaMaterialIdMedidaMaterial();
                    materialConstruccionListNewMaterialConstruccion.setMedidaMaterialIdMedidaMaterial(medidaMaterial);
                    materialConstruccionListNewMaterialConstruccion = em.merge(materialConstruccionListNewMaterialConstruccion);
                    if (oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion != null && !oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion.equals(medidaMaterial)) {
                        oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion.getMaterialConstruccionList().remove(materialConstruccionListNewMaterialConstruccion);
                        oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion = em.merge(oldMedidaMaterialIdMedidaMaterialOfMaterialConstruccionListNewMaterialConstruccion);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = medidaMaterial.getIdMedidaMaterial();
                if (findMedidaMaterial(id) == null) {
                    throw new NonexistentEntityException("The medidaMaterial with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            MedidaMaterial medidaMaterial;
            try {
                medidaMaterial = em.getReference(MedidaMaterial.class, id);
                medidaMaterial.getIdMedidaMaterial();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The medidaMaterial with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<MaterialConstruccion> materialConstruccionListOrphanCheck = medidaMaterial.getMaterialConstruccionList();
            for (MaterialConstruccion materialConstruccionListOrphanCheckMaterialConstruccion : materialConstruccionListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This MedidaMaterial (" + medidaMaterial + ") cannot be destroyed since the MaterialConstruccion " + materialConstruccionListOrphanCheckMaterialConstruccion + " in its materialConstruccionList field has a non-nullable medidaMaterialIdMedidaMaterial field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(medidaMaterial);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<MedidaMaterial> findMedidaMaterialEntities() {
        return findMedidaMaterialEntities(true, -1, -1);
    }

    public List<MedidaMaterial> findMedidaMaterialEntities(int maxResults, int firstResult) {
        return findMedidaMaterialEntities(false, maxResults, firstResult);
    }

    private List<MedidaMaterial> findMedidaMaterialEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(MedidaMaterial.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public MedidaMaterial findMedidaMaterial(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(MedidaMaterial.class, id);
        } finally {
            em.close();
        }
    }

    public int getMedidaMaterialCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<MedidaMaterial> rt = cq.from(MedidaMaterial.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
